package cn.chaozhoubang.vmall.backend.interceptor;

import cn.chaozhoubang.vmall.backend.annotation.AuthRequire;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            AuthRequire authRequire = ((HandlerMethod) handler).getMethodAnnotation(AuthRequire.class);
            if(authRequire == null || !authRequire.value()) return true;
            final String key = "key";
            String token = request.getHeader(HttpHeaders.AUTHORIZATION);
            if(token == null) return false;
            JWT jwt = JWTUtil.parseToken(token);
            boolean verifyKey = jwt.setKey(key.getBytes()).verify();
            if(!verifyKey) return false;
            String username = jwt.getPayloads().getStr("username");
            if(request.getSession().getAttribute("username") == null)
                request.getSession().setAttribute("username", username);
            return true;
        }
        return super.preHandle(request, response, handler);
    }
}
